<?php

namespace App\Helpers;

use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
use Exception;

class AliyunHelper
{
    /**
     * 执行图片安全检测（高级版）
     * 
     * @param string $imageUrl 图片URL
     * @param string $scene 检测场景（默认为postImageCheck）
     * @return array
     */
    public static function imageAdvancedCheck($imageUrl, $scene = 'postImageCheck')
    {
        try {
            /** @var Green $green */
            $green = app('aliyun.green');
            
            $request = new ImageModerationRequest([
                'service' => 'image_advanced',
                'serviceParameters' => json_encode([
                    'imageUrl' => $imageUrl,
                    'scenes' => [$scene]
                ])
            ]);
            
            $response = $green->imageModeration($request);
            return $response->body->toMap();
            
        } catch (Exception $e) {
            logger()->error('阿里云图片安全检测失败', [
                'error' => $e->getMessage(),
                'url' => $imageUrl
            ]);
            
            return [
                'code' => 500,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 生成OSS文件URL
     * 
     * @param string $path OSS文件路径
     * @return string
     */
    public static function ossUrl($path)
    {
        $endpoint = config('aliyun.oss.endpoint');
        $bucket = config('aliyun.oss.bucket');
        
        return "https://{$bucket}.{$endpoint}/" . ltrim($path, '/');
    }
}
